<!-- src/components/Calendar/PictureReader.vue -->
<template>
  <div class="picture-reader-overlay" @click="handleOverlayClick">
    <div class="picture-reader" @click.stop>
      <div class="picture-reader-header">
        <h3>图片上传</h3>
        <el-button 
          class="close-btn" 
          type="text" 
          :icon="Close" 
          @click="close"
        />
      </div>
      
      <div class="picture-reader-content">
        <!-- 拖拽上传区域 -->
        <div 
          class="upload-area"
          :class="{ 'drag-over': isDragOver }"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @dragleave="handleDragLeave"
          @click="triggerFileInput"
        >
          <div class="upload-placeholder">
            <el-icon size="48" class="upload-icon"><UploadFilled /></el-icon>
            <p>点击或拖拽图片到此处上传</p>
            <p class="upload-hint">支持 JPG、PNG、GIF 格式</p>
          </div>
          <input
            ref="fileInput"
            type="file"
            accept="image/*"
            @change="handleFileSelect"
            style="display: none"
          />
        </div>

        <!-- 图片预览 -->
        <div v-if="previewUrl" class="preview-section">
          <div class="preview-header">
            <span>图片预览</span>
            <el-button 
              type="danger" 
              text 
              :icon="Delete" 
              @click="clearPreview"
            >
              清除
            </el-button>
          </div>
          <div class="preview-image">
            <img :src="previewUrl" alt="预览图片" />
          </div>
          <div class="preview-info">
            <p>文件名: {{ selectedFile?.name }}</p>
            <p>大小: {{ formatFileSize(selectedFile?.size) }}</p>
          </div>
        </div>
      </div>

      <div class="picture-reader-footer">
        <el-button @click="close">取消</el-button>
        <el-button 
          type="primary" 
          :loading="uploading" 
          :disabled="!selectedFile"
          @click="handleUpload"
        >
          确认上传
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Close, UploadFilled, Delete } from '@element-plus/icons-vue'
import { usePictureStore } from '@/store/picture'
import type { UploadPicture } from '@/types/picture'

const emit = defineEmits<{
  close: []
}>()

const pictureStore = usePictureStore()
const fileInput = ref<HTMLInputElement>()
const isDragOver = ref(false)
const selectedFile = ref<File | null>(null)
const previewUrl = ref<string>('')
const uploading = ref(false)

// 点击外部关闭
const handleOverlayClick = (event: MouseEvent) => {
  if ((event.target as HTMLElement).classList.contains('picture-reader-overlay')) {
    close()
  }
}

// 键盘事件监听
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    close()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

const close = () => {
  emit('close')
}

// 拖拽事件处理
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    handleFile(files[0])
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 文件选择处理
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    handleFile(file)
  }
}

// 处理文件
const handleFile = (file: File) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小 (限制为 10MB)
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 10MB')
    return
  }

  selectedFile.value = file
  
  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
}

// 清除预览
const clearPreview = () => {
  selectedFile.value = null
  previewUrl.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return '0 B'
  
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

// 上传图片
const handleUpload = async () => {
  if (!selectedFile.value) return

  uploading.value = true

  try {
    const pictureData: UploadPicture = {
      file: selectedFile.value,
      name: selectedFile.value.name,
      size: selectedFile.value.size,
      type: selectedFile.value.type
    }

    await pictureStore.uploadPicture(pictureData)
    
    ElMessage.success('图片上传成功')
    close()
  } catch (error) {
    ElMessage.error('图片上传失败，请重试')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.picture-reader-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.picture-reader {
  width: 500px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}

.picture-reader-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.picture-reader-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.picture-reader-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: #409eff;
  background: #f0f7ff;
}

.upload-placeholder {
  color: #909399;
}

.upload-icon {
  margin-bottom: 12px;
  color: #c0c4cc;
}

.upload-hint {
  font-size: 12px;
  margin-top: 8px;
  color: #c0c4cc;
}

.preview-section {
  margin-top: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e0e0e0;
}

.preview-image {
  padding: 16px;
  text-align: center;
  background: #fafafa;
}

.preview-image img {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}

.preview-info {
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #e0e0e0;
  font-size: 12px;
  color: #666;
}

.preview-info p {
  margin: 4px 0;
}

.picture-reader-footer {
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>